package NC74_数字在升序数组中出现的次数;

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
        if (array == null || array.length == 0){
            return 0;
        }
        int length = array.length;
        int firstIndex = getFirstIndex(array, k, 0, length - 1);
        int lastIndex = getLastIndex(array, k, 0, length - 1);

        if (firstIndex != -1 && lastIndex != -1){
            return lastIndex - firstIndex + 1;
        }
        return 0;
    }
    // 循环写法
    private int getLastIndex(int[] array, int k, int start, int end) {
        int length = array.length;
        int mid = (start + end) >> 1;

        while (start <= end){
            if (array[mid] > k){
                end = mid - 1;
            }else if (array[mid] < k){
                start = mid + 1;
            }else if (mid < length - 1 && array[mid + 1] == k){
                start = mid + 1;
            }else {
                return mid;
            }
            mid = (start + end) >> 1;
        }
        return -1;
    }

    private int getFirstIndex(int[] array, int k, int start, int end) {
        if (start > end){
            return -1;
        }
        int mid = (start + end) >> 1;
        if (array[mid] > k){
            return getFirstIndex(array, k, start, mid - 1);
        }else if (array[mid] < k){
            return getFirstIndex(array, k, mid + 1, end);
        }else if (mid > 0 && array[mid - 1] == k){
            return getFirstIndex(array, k, start, mid - 1);
        }else {
            return mid;
        }
    }
}
